package cc.mrbird.febs.material.service.impl;

import cc.mrbird.febs.common.domain.QueryRequest;
import cc.mrbird.febs.common.utils.SortUtil;
import cc.mrbird.febs.material.domain.MaterialLibrary;
import cc.mrbird.febs.material.dao.MaterialLibraryMapper;
import cc.mrbird.febs.material.service.IMaterialLibraryService;
import cc.mrbird.febs.system.domain.Role;
import cc.mrbird.febs.system.domain.Test;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author mg
 */
@Slf4j
@Service("materialLibraryService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class MaterialLibraryServiceImpl extends ServiceImpl<MaterialLibraryMapper, MaterialLibrary> implements IMaterialLibraryService {

    @Value("${febs.max.batch.insert.num}")
    private int batchInsertMaxNum;
    @Override
    public List<MaterialLibrary> findTests() {
        try {
            return baseMapper.selectList(new QueryWrapper<MaterialLibrary>().orderByDesc("create_time"));
        } catch (Exception e) {
            log.error("获取信息失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    @Transactional
    public void batchInsert(List<MaterialLibrary> list) {
        saveBatch(list, batchInsertMaxNum);
    }

    @Override
    public IPage<MaterialLibrary> findMaterialLibrary(MaterialLibrary materialLibrary, QueryRequest queryRequest) {
        try {
            LambdaQueryWrapper<MaterialLibrary> queryWrapper = new LambdaQueryWrapper<>();

            if (StringUtils.isNotBlank(materialLibrary.getName())) {
                queryWrapper.like(MaterialLibrary::getName, materialLibrary.getName());
            }
            if (StringUtils.isNotBlank(materialLibrary.getCreateTimeFrom()) && StringUtils.isNotBlank(materialLibrary.getCreateTimeTo())) {
                queryWrapper
                        .ge(MaterialLibrary::getCreateTime, materialLibrary.getCreateTimeFrom())
                        .le(MaterialLibrary::getCreateTime, materialLibrary.getCreateTimeTo());
            }
            Page<MaterialLibrary> page = new Page<>();
            SortUtil.handlePageSort(queryRequest, page, true);
            return this.page(page,queryWrapper);
        } catch (Exception e) {
            log.error("获取物资信息失败", e);
            return null;
        }
    }
}
